<?php

namespace Frontend\Controllers;

use DuAdmin\Core\BaseController;
use Frontend\Forms\PasswordResetRequestForm;
use Frontend\Forms\ResetPasswordForm;
use InvalidArgumentException;
use Yii;
use yii\web\BadRequestHttpException;

class ForgetPasswordController extends BaseController
{
    public function actionIndex()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', Yii::t('theme', 'Check your email for further instructions'));
                return $this->render('email-send-success', ['model' => $model]);
            } else {
                Yii::$app->session->setFlash('error', Yii::t('theme', 'Sorry, we are unable to reset password for the provided email address'));
            }
        }
        return $this->render('index', [
            'model' => $model
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException::
     */
    public function actionReset($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', Yii::t('theme', 'New password saved'));
            return $this->render("reset-success");
        }
        return $this->render('reset', [
            'model' => $model
        ]);
    }
}
